/**
 * Created by lmzpc on 2015/11/10.
 */

//配置view参数
RED.view = (function () {

    var scaleFactor = 1,
        node_width = 140,
        node_height = 30;

    var viewOptions = {
        space: {
            space_width: 5000,
            space_height: 5000
        },
        status_colors: {
            "red": "#c00",
            "green": "#5a8",
            "yellow": "#F9DF31",
            "blue": "#53A3F3",
            "grey": "#d3d3d3"
        },

        "mouse_mode": 0,
        "dblClickPrimed": true,//允许双击打开对话框
        "clickElapsed": 0,
        'mousedown_node': null,//当前鼠标按下的Node
        'lastClickNode': null,//上次点击的node
        'clickTime': 0,//点击的时间
    };


    //workspace 对应的数据模型
    var graph = new joint.dia.Graph;
    
    var paper = new joint.lmz.Paper({
        el: $('#chart'),
        snapLinks: true,
        linkPinning: false,
        defaultLink: new joint.shapes.uml.Transition,
        width: viewOptions.space.space_width,
        height: viewOptions.space.space_height,
        model: graph,
        markAvailable: true,
        interactive: true
    }).on({
        'cell:pointerup': function (cellView,evt) {

            if (cellView.model instanceof joint.dia.Link) return;
            if (cellView.model instanceof joint.dia.Element) {
                if(evt.shiftKey){
                    var halo = new joint.ui.Halo({cellView: cellView, showLabel: false});
                    halo.removeHandle("clone");
                    halo.removeHandle("link");
                    halo.removeHandle("fork");
                    halo.removeHandle("remove");

                    halo.render();
                    halo.on('action:link:add', function () {
                        console.log('link added');
                    });
                }else{
                    this.clearSelection();
                    this.selectView(cellView);
                }


            }

            if(cellView.model instanceof  joint.shapes.fsa.State){

            }

        },
        'blank:pointerclick': function () {
            this.clearSelection();
        },
    });

    initStencil(paper);

    function initStencil(paper) {

        //工具栏
        var stencil = new joint.ui.Stencil({
            paper: paper,
            height: 100
        });
        $('#state_machine').append(stencil.render().el);

        stencil.load([
            new joint.shapes.uml.StartState({size: {width: 30, height: 30},}),
            new joint.shapes.uml.EndState({size: {width: 30, height: 30}}),
            new joint.shapes.fsa.State({size: {width: 30, height: 30},replace:new joint.shapes.uml.State({size:{width:50,height:100}})})
        ]);

        joint.layout.GridLayout.layout(stencil.getGraph(), {
            columns: 100,
            columnWidth: 40,
            rowHeight: 30,
            dy: 5,
            dx: 5
        });

        stencil.getPaper().fitToContent(0, 0, 10);
    };


    function calculateTextWidth(str, className, offset) {
        var sp = document.createElement("span");
        sp.className = className;
        sp.style.position = "absolute";
        sp.style.top = "-1000px";
        sp.innerHTML = (str || "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        document.body.appendChild(sp);
        var w = sp.offsetWidth;
        document.body.removeChild(sp);
        return offset + w;
    }

    function focusView() {
        $("#chart svg").focus();
    }

    //定义droppable,sidder的元素dragto space
    function init() {

        $("#chart").droppable({
            drop: function (event, ui) {
                d3.event = event;
                if (d3.event) {
                    d3.event.preventDefault();
                }
                var m = /^subflow:(.+)$/.exec(selected_tool);

                var selected_tool = ui.draggable[0].type;

                var mousePos = d3.touches(this)[0] || d3.mouse(this);
                mousePos[1] += this.scrollTop;
                mousePos[0] += this.scrollLeft;
                mousePos[1] /= scaleFactor;
                mousePos[0] /= scaleFactor;

                var nn = {
                    id: (1 + Math.random() * 4294967295).toString(16),
                    x: mousePos[0],
                    y: mousePos[1],
                    w: node_width,
                    z: RED.workspaces.active()
                };

                nn.type = selected_tool;
                nn._def = RED.nodes.getType(nn.type);

                if (!m) {
                    nn.inputs = nn._def.inputs || 0;
                    nn.outputs = nn._def.outputs;

                    for (var d in nn._def.defaults) {
                        if (nn._def.defaults.hasOwnProperty(d)) {
                            nn[d] = nn._def.defaults[d].value;
                        }
                    }

                    if (nn._def.onadd) {
                        nn._def.onadd.call(nn);
                    }
                } else {
                    var subflow = RED.nodes.subflow(m[1]);
                    nn.inputs = subflow.in.length;
                    nn.outputs = subflow.out.length;
                }


                nn.changed = true;
                nn.h = Math.max(node_height, (nn.outputs || 0) * 15);
                //updateActiveNodes(nn);

                addCells(nn);
            }
        });
        RED.keyboard.add(/* z */ 90, {ctrl: true}, function () {
            RED.history.pop();
        });
        RED.keyboard.add(/* a */ 65, {ctrl: true}, function () {
            paper.selectAll();
            d3.event.preventDefault();
        });
        RED.keyboard.add(/* = */ 187, {ctrl: true}, function () {
            zoomIn();
            d3.event.preventDefault();
        });
        RED.keyboard.add(/* - */ 189, {ctrl: true}, function () {
            zoomOut();
            d3.event.preventDefault();
        });
        RED.keyboard.add(/* 0 */ 48, {ctrl: true}, function () {
            zoomZero();
            d3.event.preventDefault();
        });
        RED.keyboard.add(/* v */ 86, {ctrl: true}, function () {
            importNodes(clipboard);
            d3.event.preventDefault();
        });
        RED.keyboard.add(/* backspace */ 8, function () {

            paper.deleteSelection();
            d3.event.preventDefault();
        });
        RED.keyboard.add(/* delete */ 46,function(){ paper.deleteSelection();d3.event.preventDefault();});
        RED.keyboard.add(/* c */ 67,{ctrl:true},function(){paper.copySelection();d3.event.preventDefault();});
    }

    function addCells(nn) {
        graph.addCell(new joint.shapes.origin.Base(
            {
                position: {x: nn.x, y: nn.y},
                size: {width: 140, height: 30},
                data: nn,
                paper: paper,
                graph:graph
            }
        ));
    }

    function redraw() {
        console.log('redraw is cancled!');
    }

    return {
        init: init,
        focus: focusView,
        calculateTextWidth: calculateTextWidth,
        viewOptions: viewOptions,
        state: function (state) {
            if (state == null) {
                return mouse_mode
            } else {
                mouse_mode = state;
            }
        },

    };
})
();


//var drag_line = d3.select("#chart svg g").append("svg:path").attr("class", "drag_line");




